#include <iostream>
#include <string>
#include <cstdlib>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

// father -> read
// child -> write
int main() 
{
    // 1. 创建管道
    int fds[2] = {0};
    int n = pipe(fds);  // fds是输出型参数
    if (n != 0)
    {
        std::cerr << "pipe failed" << std::endl;
        return 1;
    }

    // 2.创建子进程
    pid_t id = fork();
    if (id < 0)
    {
        std::cerr << "fork failed" << std::endl;
        return 2;
    } 
    else if (id == 0)
    {
        // 子进程读
        // 3.关闭不需要的fd,关闭读端
        close(fds[0]);
        int cnt = 0;
        int total = 0;
        while(true)
        {
            //std::string message = "h";
            std::string message = "hello child, hello ";
            message += std::to_string(getpid());
            message += ", ";
            message += std::to_string(cnt);

            total += ::write(fds[1], message.c_str(), message.size());
            //std::cout << "total: " << total << std::endl;
            cnt++;
            sleep(10);
            //break;
        }
        exit(0);
    }
    else
    {
        // 父进程
        // 3.关闭不需要的fd,关闭写端
        close(fds[1]);

        char buffer[5];
        while(true)
        {
            ssize_t n = ::read(fds[0], buffer, sizeof(buffer));
            if (n > 0)
            {
                buffer[n] = 0;
                std::cout << "child->father, message: " << buffer << std::endl;
            }
            else if (n == 0)
            {
                std::cout << "child quit? me too!" << std::endl;
                break;
            }
            //close(fds[0]);
            //sleep(1);
            //break;
            //std::cout << std::endl;
        }

        int status;
        pid_t rid = waitpid(id, &status, 0);
        std::cout << "farther wait child success: " << rid  << ",exit code: " << WEXITSTATUS(status) << ",signal: " << WTERMSIG(status) <<std::endl;

    }

    return 0;
}